import React from 'react'

function ToDoItem(props) {
    return (
        <ol>
            <input type='text' value={props.value} onChange={props.input.bind(this,props.index)} onBlur={props.blur.bind(this)}/>
            <button onClick={props.delete.bind(this,props.index)}> × </button>
        </ol>
    )
}

class ToDoList extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            todolist:[],
            typing:'',
        }
        this.add = this.add.bind(this)
        this.delete = this.delete.bind(this)
        this.input = this.input.bind(this)
        this.save = this.save.bind(this)
    }

    componentDidMount(){
        let localStore = localStorage.getItem('react_todolist');
        if (localStore){
            this.setState({
                todolist:JSON.parse(localStore),
            })
        }
    }

    add(){
        if(!this.state.typing.trim()){
            alert('内容不能为空')
            return;
        }
        const obj = {
            value:this.state.typing,
            status:0
        }
        let data = this.state.todolist;
        data.push(obj);
        this.setState({
            todolist:data,
            typing:''
        })
        console.log('after added:',this.state.todolist);
        this.save();
    }

    delete(index){
        console.log('delete:',index)
        let data = this.state.todolist;
        data.splice(index,1)
        this.setState({
            todolist:data
        })
        console.log(this.state.todolist)
        this.save();
    }

    input(index,e){
        let value = e.target.value;
        let data = this.state.todolist;
        data[index].value = value;
        this.setState({
            todolist:data
        })
    }


    change(e){
        this.setState({
            typing:e.target.value
        })
    }

    save(e){
        localStorage.setItem('react_todolist',JSON.stringify(this.state.todolist))
        // e.preventDefault();
    }

    render(){
        const list = this.state.todolist.map((item,index)=>
            <ToDoItem key={index} value={item.value} index={index} delete={this.delete} input={this.input} blur={this.save}/>
        )
        return (
            <div>
                <ul>
                    {list}
                    <ol>
                        <input type='text' value={this.state.typing} onChange={this.change.bind(this)}/>
                        <button onClick={this.add.bind(this)}> + </button>
                    </ol>
                </ul>
                <pre>Typing:{this.state.typing}</pre>
            </div>
        )
    }
}

export default ToDoList;